package org.spawndb.impl.mysql;

import org.spawndb.ISpawnDBManager;
import com.mysql.management.MysqldResource;

import java.io.File;
import java.util.Map;
import java.util.HashMap;


public class MYSQLManager implements ISpawnDBManager {

    private MysqldResource mysqldResource;
    private Map<String,String> options= new HashMap<String,String>();
    private String baseDir = System.getProperty("user.home")+"/db/mysql";
    private String dataDir;
    private boolean running=false;
    //private static final Logger log = Logger.getLogger("MYSQLManager");

    public MYSQLManager(){
    }

    public void setBaseDir(String baseDir) {
        this.baseDir=baseDir;
    }

    @Override
    public void setDataDir(String dataDir) {
        this.dataDir=dataDir;
    }

    public void setDBProperties(Map options){
        this.options=options;
    }

    public void start() throws Exception {
        if(running) throw new Exception("db is already running");
        if(mysqldResource==null){
            File dbRootDir = new File(baseDir);
            if(!dbRootDir.exists()) dbRootDir.mkdirs();
            mysqldResource = new MysqldResource(dbRootDir);
        }
        //options.put(MysqldResourceI.INITIALIZE_USER, "true");
        //options.put(MysqldResourceI.INITIALIZE_USER_NAME, "easa_user");
        //options.put(MysqldResourceI.INITIALIZE_PASSWORD, "easa_user");
        mysqldResource.start("mysqld-thread", options);
        if (!mysqldResource.isRunning()) {
            throw new RuntimeException("MySQL did not start.");
        }
        running=true;
        System.out.println("MySQL is running.");

    }

    public void stop() throws Exception {
        if(!running) throw new Exception("db is already stopped");
        if(mysqldResource==null){
            File dbRootDir = new File(baseDir);
            mysqldResource = new MysqldResource(dbRootDir);
        }
        System.out.println("Shutting down MySQL");
        mysqldResource.shutdown();
        running=false;
    }

    @Override
    public File getDataDir() {
        if(mysqldResource==null) return null;
        return mysqldResource.getDataDir();
    }

    @Override
    public File getBaseDir() {
        if(mysqldResource==null) return null;        
        return mysqldResource.getBaseDir();
    }

    @Override
    public String getDBVendor() {
        return "mysql";
    }


}

